import axios from "axios";
import router from "@/router";
import { MessageBox, Message, Loading } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import { parseTime, getOsInfo, getBrowser,getCookie } from "@/utils/index.js";

let loading = null;

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // timeout: 5000 // request timeout
});
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";

// request interceptor
service.interceptors.request.use(
  config => {
    loading=  Loading.service({});
    config.headers["Authorization"] = "Basic b3JnbjoxMjM0NTY=";
    if (store.getters.token) {
      config.headers["Authorization"] = "Bearer " + getToken();
      config.headers["X-XSRF-TOKEN"] = getCookie("XSRF-TOKEN")
    }
    if ( parseInt(config.url.indexOf('?'))   > parseInt(-1)) {
      let configlist=config.url.split('?')
      config.url=configlist[0]+'.json?'+configlist[1]
    } else {
      config.url=config.url+'.json'
    }

    // 拦截get请求，将params参数通过 encodeURIComponent 函数转换成编码
    if(config.method === 'get'){
      for (const key in config.params) {
        if (Object.hasOwnProperty.call(config.params, key)) {
          let left = encodeURIComponent('[')
          let right = encodeURIComponent(']')
          typeof config.params[key] === 'string' && (config.params[key].indexOf('[') > -1 || config.params[key].indexOf(']') > -1 ) ?
           config.params[key] =  config.params[key].replace(/\[/g,left).replace(/\]/g,right) : ''
        }
      }
    }
    return config;
  },
  error => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);


let timer = null;

// response interceptor
service.interceptors.response.use(
  response => {

    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      if (loading) {
        loading.close();
        loading=null
      }
    }, 1000);
    
    const res = response.data;

    // if (!res.isSuccess) {
    //   alert('失败')
    // }

    if(res.failureCode&&res.failureCode == '7001'){
       alert(res.failureMessage)
       window.location.reload()
       return false
    }

    // res.failureCode && res.failureCode == '020001' && store.dispatch("user/resetToken").then(() => {
    //   router.next('/login')
    // })

    return res;
  },
  error => {
  
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
        loading.close();
        loading=null
    }, 1000);

    // console.log("err response:" + JSON.stringify(error.response.config.url)); // for debug
    // console.log("err :" + error.message); // for debug
    // let logger = {
    //   type: 'network',
    //   // status: error.response.status,
    //   message: error.message,
    //   url: error.response.config.url,
    //   time: parseTime(new Date()),
    //   OsInfo: getOsInfo(),
    //   Browser: getBrowser(),
    //   cip: returnCitySN["cip"],
    //   city: returnCitySN["cname"],
    // }

    // store.dispatch('errorLog/addErrorLog', logger)

    // if (timer) {
    //   clearTimeout(timer);
    // }

    // timer = setTimeout(() => {
    //   Message({
    //     message: error.message,
    //     type: "error",
    //   });
    // }, 100)
    return Promise.reject('error');

  }
);

export default service;
